<template>
  <div class="login">
    <!-- 语言切换组件 - 放置在右上角 -->
    <div class="lang-select-container"><lang-select/></div>
    <div style="width:150px"></div>
    <el-form ref="loginForm" :model="loginForm" :rules="loginRules" class="login-form">
      <h3 class="title">{{ safeTranslate('login.title','登录') }}</h3>
      <!-- <p class="smtit">{{ safeTranslate('login.subtitle','LOGIN SYSTEM') }}</p> -->
      <el-form-item prop="username">
        <el-input v-model="loginForm.username" type="text" auto-complete="off" :placeholder="safeTranslate('login.username','账号')">
          <svg-icon slot="prefix" icon-class="user" class="el-input__icon input-icon" />
        </el-input>
      </el-form-item>
      <el-form-item prop="password">
        <el-input v-model="loginForm.password" type="password" auto-complete="off" :placeholder="safeTranslate('login.password','密码')" @keyup.enter.native="handleLogin">
          <svg-icon slot="prefix" icon-class="password" class="el-input__icon input-icon" />
        </el-input>
      </el-form-item>
      <el-form-item prop="code" v-if="captchaEnabled">
        <el-input v-model="loginForm.code" auto-complete="off" :placeholder="safeTranslate('login.captcha','验证码')" style="width:63%" @keyup.enter.native="handleLogin">
          <svg-icon slot="prefix" icon-class="validCode" class="el-input__icon input-icon" />
        </el-input>
        <div class="login-code"><img :src="codeUrl" @click="getCode" class="login-code-img"/></div>
      </el-form-item>
      <el-checkbox v-model="loginForm.rememberMe" style="margin:0px 0px 25px 0px;">
        {{ safeTranslate('login.rememberMe', '记住密码') }}
      </el-checkbox>
      <el-form-item style="width:100%;">
        <el-button :loading="loading" size="medium" type="primary" style="width:100%;" @click.native.prevent="handleLogin">
          <span v-if="!loading">{{ safeTranslate('login.login', '登 录') }}</span>
          <span v-else>{{ safeTranslate('login.loggingIn', '登 录 中...') }}</span>
        </el-button>
        <div style="float: right;" v-if="register">
          <router-link class="link-type" :to="'/register'">{{ safeTranslate('login.register', '立即注册') }}</router-link>
        </div>
      </el-form-item>
    </el-form>
    <!--  底部  -->
    <div class="el-login-footer">
      <span style="font-size:18px;">Copyright © 2018-2099 苏ICP备2023025724号</span>
    </div>
  </div>
</template>

<script>
import { getCodeImg } from "@/api/login";
import Cookies from "js-cookie";
import { encrypt, decrypt } from '@/utils/jsencrypt'

export default {
  name: "Login",
  data() {
    return {
      codeUrl: "",
      loginForm: {
        username: "",
        password: "",
        rememberMe: false,
        code: "",
        uuid: ""
      },
      loginRules: {
        username: [
          { required: true, trigger: "blur", message: '请输入您的账号' }
        ],
        password: [
          { required: true, trigger: "blur", message: '请输入您的密码' }
        ]
        // 注意：code 的验证规则在 created 中动态设置
      },
      loading: false,
      captchaEnabled: true,
      register: true,
      redirect: undefined,
      isI18nReady: false
    };
  },
  watch: {
    // 监听语言变化，更新验证规则
    '$i18n.locale'() {
      this.updateValidationRules();
    },
    $route: {
      handler: function(route) {
        this.redirect = route.query && route.query.redirect;
      },
      immediate: true
    }
  },
  mounted() {
    // 组件挂载后更新验证规则
    this.$nextTick(() => {
      this.updateValidationRules();
    });
  },
  created() {
    this.getCode();
    this.getCookie();
    this.waitForI18n();
  },
  methods: {
    // 安全的翻译方法
    safeTranslate(key, defaultValue) {
      if (this.isI18nReady && this.$t) {
        try {
          const result = this.$t(key);
          return result === key ? defaultValue : result;
        } catch (error) {
          return defaultValue;
        }
      }
      return defaultValue;
    },

    // 等待i18n就绪
    waitForI18n() {
      if (this.$i18n && typeof this.$t === 'function') {
        this.isI18nReady = true;
        this.updateValidationRules();
      } else {
        setTimeout(() => {
          this.waitForI18n();
        }, 50);
      }
    },

    // 更新验证规则
    updateValidationRules() {
      if (!this.isI18nReady) return;

      try {
        // 创建新的验证规则对象
        const newRules = {
          username: [
            {
              required: true,
              trigger: "blur",
              message: this.safeTranslate('login.usernameRequired', '请输入您的账号')
            }
          ],
          password: [
            {
              required: true,
              trigger: "blur",
              message: this.safeTranslate('login.passwordRequired', '请输入您的密码')
            }
          ]
        };

        // 只有在需要验证码时才添加 code 的验证规则
        if (this.captchaEnabled) {
          newRules.code = [
            {
              required: true,
              trigger: "change",
              message: this.safeTranslate('login.captchaRequired', '请输入验证码')
            }
          ];
        }

        // 使用 Object.assign 确保响应式更新
        Object.assign(this.loginRules, newRules);

        // 清除表单验证状态
        if (this.$refs.loginForm) {
          this.$nextTick(() => {
            this.$refs.loginForm.clearValidate();
          });
        }
      } catch (error) {
        console.warn('Error updating validation rules:', error);
      }
    },

    getCode() {
      getCodeImg().then(res => {
        const wasCaptchaEnabled = this.captchaEnabled;
        this.captchaEnabled = res.captchaEnabled === undefined ? true : res.captchaEnabled;

        // 如果验证码状态发生变化，更新验证规则
        if (wasCaptchaEnabled !== this.captchaEnabled) {
          this.updateValidationRules();
        }

        if (this.captchaEnabled) {
          this.codeUrl = "data:image/gif;base64," + res.img;
          this.loginForm.uuid = res.uuid;
        } else {
          // 如果不需要验证码，清空相关字段
          this.loginForm.code = "";
          this.loginForm.uuid = "";
        }
      }).catch(error => {
        console.error('获取验证码失败:', error);
        this.captchaEnabled = false;
        this.updateValidationRules();
      });
    },

    getCookie() {
      const username = Cookies.get("username");
      const password = Cookies.get("password");
      const rememberMe = Cookies.get('rememberMe')
      this.loginForm = {
        username: username === undefined ? this.loginForm.username : username,
        password: password === undefined ? this.loginForm.password : decrypt(password),
        rememberMe: rememberMe === undefined ? false : Boolean(rememberMe),
        code: "", // 确保 code 为空
        uuid: this.loginForm.uuid
      };
    },

    handleLogin() {
      this.$refs.loginForm.validate(valid => {
        if (valid) {
          this.loading = true;
          if (this.loginForm.rememberMe) {
            Cookies.set("username", this.loginForm.username, { expires: 30 });
            Cookies.set("password", encrypt(this.loginForm.password), { expires: 30 });
            Cookies.set('rememberMe', this.loginForm.rememberMe, { expires: 30 });
          } else {
            Cookies.remove("username");
            Cookies.remove("password");
            Cookies.remove('rememberMe');
          }

          // 准备提交的数据
          const loginData = {
            username: this.loginForm.username,
            password: this.loginForm.password,
            rememberMe: this.loginForm.rememberMe,
            uuid: this.loginForm.uuid
          };

          // 只有在需要验证码时才添加 code
          if (this.captchaEnabled) {
            loginData.code = this.loginForm.code;
          }

          this.$store.dispatch("Login", loginData).then(() => {
            this.$router.push({ path: "/bigScreen" }).catch(()=>{});
          }).catch(() => {
            this.loading = false;
            if (this.captchaEnabled) {
              this.getCode();
            }
          });
        }
      });
    }
  }
};
</script>

<style rel="stylesheet/scss" lang="scss">
.login {
  padding-top: 200px;
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
  background-image: url("../assets/images/loginbg.png");
  background-size: cover;
  position: relative;
}

/* 语言选择器容器 - 固定在右上角 */
.lang-select-container {
  position: absolute;
  top: 20px;
  right: 20px;
  z-index: 999;
}

.title {
  padding-left: 30px;
  margin: 0px auto 30px auto;
  text-align: center;
  color: #1c84c6;
  font-size: 30px;
  letter-spacing: 50px;
}

.smtit {
  padding-left: 85px;
  font-size: 20px;
  color: #1c84c6;
}

//登陆框
.login-form {
  margin-left: 50%;
  border-radius: 8px;
  background: rgba(53, 76, 110, 0.8);
  width: 400px;
  padding: 35px 35px 15px 35px;
  box-shadow: 0 4px 10px rgba(0, 0, 0, 0.2);
  color: #c0c0c0;
  font-family: 'Courier New', Courier, monospace;

  .el-input {
    height: 38px;
    input {
      height: 38px;
      border: 1px solid #ddd;
      border-radius: 4px;
      padding: 0 -5px;
      background-color: rgba(255, 255, 255, 0.2);
      color: #fff;
    }
  }
  .input-icon {
    height: 39px;
    width: 14px;
    margin-left: 2px;
    fill: #fff;
  }
}

.login-tip {
  font-size: 13px;
  text-align: center;
  color: #bfbfbf;
  font-style: italic;
}

.login-code {
  width: 33%;
  height: 38px;
  float: right;
  img {
    cursor: pointer;
    vertical-align: middle;
  }
}

.el-login-footer {
  height: 40px;
  line-height: 40px;
  position: fixed;
  bottom: 0;
  width: 100%;
  text-align: center;
  color: #fff;
  font-family: Arial;
  font-size: 12px;
  letter-spacing: 1px;
}

.login-code-img {
  height: 38px;
}

.cssk {
  width: 30%;
}

.tt {
  margin-top: -210%;
}

.international-icon {
  display: flex;
  align-items: center;
  padding: 8px 12px;
  background: rgba(255, 255, 255, 0.1);
  border-radius: 4px;
  transition: all 0.3s;
  color: #fff;
}

.international-icon:hover {
  background: rgba(255, 255, 255, 0.2);
}

.language-text {
  margin-left: 5px;
  font-size: 14px;
}
</style>
